from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from django.db import transaction
from django.utils import timezone
from .models import Order, OrderItem
from .serializers import OrderSerializer, OrderItemSerializer
from apps.cart.models import CartItem
from apps.address.models import Address
from apps.product.models import Product
from utils.permissions import IsOwnerOrAdmin
from utils.response import api_response
from apps.product.models import SKU

class OrderViewSet(viewsets.ModelViewSet):
    serializer_class = OrderSerializer
    permission_classes = [IsAuthenticated, IsOwnerOrAdmin]

    def get_queryset(self):
        if self.request.user.is_staff:
            return Order.objects.all()
        return Order.objects.filter(user=self.request.user)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    @action(detail=False, methods=['post'])
    def create_order(self, request):
        """创建订单"""
        address_id = request.data.get('address_id')
        items = request.data.get('items', [])
        remark = request.data.get('remark', '')

        # 参数验证
        if not address_id:
            return Response({
                'code': 400,
                'message': '请选择收货地址'
            }, status=status.HTTP_400_BAD_REQUEST)

        if not items:
            return Response({
                'code': 400,
                'message': '订单商品不能为空'
            }, status=status.HTTP_400_BAD_REQUEST)

        try:
            address = Address.objects.get(id=address_id, user=request.user)
        except Address.DoesNotExist:
            return Response({
                'code': 404,
                'message': '收货地址不存在'
            }, status=status.HTTP_404_NOT_FOUND)

        # 创建订单
        try:
            with transaction.atomic():
                # 生成订单号
                order_number = f"{timezone.now().strftime('%Y%m%d%H%M%S')}{request.user.id:04d}"
                
                # 创建订单
                order = Order.objects.create(
                    user=request.user,
                    order_number=order_number,
                    address=address,
                    remark=remark,
                    total_amount=0  # 初始化为0，后面计算
                )

                total_amount = 0
                order_items = []

                # 创建订单项
                for item in items:
                    sku_id = item.get('sku_id')
                    quantity = int(item.get('quantity', 1))

                    if quantity <= 0:
                        raise ValueError(f'商品数量必须大于0 (SKU ID: {sku_id})')

                    try:
                        sku = SKU.objects.select_for_update().get(
                            id=sku_id,
                            is_active=True,
                            product__is_active=True
                        )
                    except SKU.DoesNotExist:
                        raise ValueError(f'商品不存在或已下架 (SKU ID: {sku_id})')

                    if quantity > sku.stock:
                        raise ValueError(f'商品库存不足 (SKU: {sku.name}, 库存: {sku.stock})')

                    # 计算小计金额
                    amount = sku.price * quantity
                    total_amount += amount

                    # 创建订单项
                    order_items.append(OrderItem(
                        order=order,
                        sku=sku,
                        quantity=quantity,
                        price=sku.price,
                        amount=amount
                    ))

                    # 扣减库存
                    sku.stock -= quantity
                    sku.save()

                # 批量创建订单项
                OrderItem.objects.bulk_create(order_items)

                # 更新订单总金额
                order.total_amount = total_amount
                order.save()

                return Response({
                    'code': 200,
                    'message': '创建成功',
                    'data': {
                        'id': order.id,
                        'order_number': order.order_number,
                        'total_amount': float(order.total_amount)
                    }
                })

        except ValueError as e:
            return Response({
                'code': 400,
                'message': str(e)
            }, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            return Response({
                'code': 500,
                'message': f'创建订单失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    @action(detail=True, methods=['post'])
    def cancel(self, request, pk=None):
        order = self.get_object()
        if order.status != 'pending':
            return api_response(400, "只能取消待支付订单")
        
        order.status = 'cancelled'
        order.save()
        return api_response(data=OrderSerializer(order).data) 